<template>
    <div>
        <!-- 表格部分 -->
        <el-table ref="singalTable" v-loading="listLoading" :data="list" :stripe="true" :height="tableHeight" fit
            :header-cell-style="{background:'#eef1f6',color:'#606266'}" :edit-config="{
              trigger: 'dblclick',
              mode: 'row',
              showStatus: true,
              activeMethod: true,
            }">
            <template slot="empty">
                <tableEmpty />
            </template>
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column type="index" align="center" width="80" label="序号" />
            <el-table-column label="工资项名称" align="center" :edit-render="{}">
                <template slot-scope="{row}">
                    <el-input class="item" v-if="row.isOperate" v-model="row.salaryName" placeholder="请输入" />
                    <span v-else>{{ row.salaryName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate && row.salaryCode !== 's1' && row.salaryCode !== 's2'">
                        <el-select v-model="row.baseState" placeholder="请选择">
                            <el-option v-for="item in dict.baseState" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.baseState | dictFilter('baseState',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否标准项" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isStandard" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isStandard | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否计算项" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isCompute" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isCompute | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="工资项类型" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.computeFormula" placeholder="请选择">
                            <el-option v-for="item in dict.withNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.computeFormula | dictFilter('withNo',that) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="月结是否清零" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isClear" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isClear | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否代扣项" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isAccsalPay" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isAccsalPay | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否代缴项" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isAccsalWithhold" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isAccsalWithhold | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否显示" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isShow" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isShow | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否校验功能分类" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-select v-model="row.isCheck" placeholder="请选择">
                            <el-option v-for="item in dict.yesOrNo" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <span v-else>{{ row.isCheck | dictFilter('yesOrNo',that) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="小数位数" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-input-number v-model="row.decimalPlace" style="width: 100%;" controls-position="right"
                            :min="0" :max="10" :step="1" step-strictly />
                    </div>
                    <span v-else>{{ row.decimalPlace }}</span>
                </template>
            </el-table-column>
            <el-table-column label="显示顺序" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-input-number v-model="row.showOrder" style="width: 100%;" controls-position="right" :min="1"
                            :max="1000" :step="1" step-strictly />
                    </div>
                    <span v-else>{{ row.showOrder }}</span>
                </template>
            </el-table-column>
            <el-table-column label="工资条顺序" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-input-number v-model="row.salaryListOrder" style="width: 100%;" controls-position="right"
                            :min="1" :max="1000" :step="1" step-strictly />
                    </div>
                    <span v-else>{{ row.salaryListOrder }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center">
                <template slot-scope="{row}">
                    <div v-if="row.isOperate">
                        <el-input v-model="row.remark" maxlength="10" placeholder="请输入" />
                    </div>
                    <span v-else>{{ row.remark }}</span>
                </template>
            </el-table-column>
        </el-table>
        <!--分页部分-->
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
</template>
<script>

import {
    queryPage,
    submitData,
    deleteBatchData
}
    from '@/api/salaryConfigManage/salaryProjectMaintenance'
import Enclosure from '@/components/Enclosure'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import PersonSalaryInfo from '@/components/personSalaryInfo/personSalaryInfo'
export default {
    name: 'Unit',
    components: { Pagination, tableEmpty, Enclosure, PersonSalaryInfo },
    directives: { waves },
    props: ['tabPane', 'treeData'],
    filters: {
        dictFilter(value, dictType, that) {
            const dict = that.dict[dictType]
            for (const item of dict) {
                if (value === item.value) {
                    return item.label
                }
            }
        }
    },
    data() {
        return {
            tableHeight: null,
            that: this,
            submitIds: [],
            submitList: [],
            addItem: {
                id: '',
                salaryName: '',
                baseState: '1',
                isStandard: 0,
                isCompute: 0,
                isCheck: 0,//是否校验功能分类
                isClear: 0,
                isAccsalPay: 0,
                isAccsalWithhold: 0,
                isShow: 1,
                decimalPlace: '',
                remark: '',
                isOperate: true,
                isNewItem: ''
            },
            list: [],
            total: 0,
            listLoading: true,
            removeBtnLoading: false,
            saveBtnLoading: false,
            listQuery: {
                page: 1,
                limit: 200
            },
            dict: {
                baseState: [
                    { label: '启用', value: '1' },
                    { label: '停用', value: '0' }
                ],
                yesOrNo: [{ label: '是', value: 1 }, { label: '否', value: 0 }],
                withNo: [{ label: '发项', value: 1 }, { label: '扣项', value: -1 }, { label: '非发非扣', value: 0 }]
            },
            agencyTree: {}
        }
    },
    watch: {
        'formData.toAgencyName'(val) {
            this.$refs.tree.filter(val)
        },
        // 表格的数据数组
        list(val) {
            this.doLayout()
        },

    },
    mounted() {
        this.getTbHeight()
    },
    beforeMount() {
        window.addEventListener('resize', this.getTbHeight)
    },
    created() {
        this.getList()

    },
    computed: {
        ids() {
            const selection = this.$refs.singalTable.selection
            const arr = []
            selection.forEach(item => {
                if (!item.isNewItem) {
                    arr.push(item.id)
                }
            })
            return arr.join(',')
        }
    },
    methods: {
        // 获取table高度的方法
        getTbHeight() {
            this.tableHeight = window.innerHeight - 300
        },
        /* 重新渲染table组件 */
        doLayout() {
            this.$nextTick(() => {
                this.$refs.singalTable.doLayout()
            })
        },
        // 查询
        query() {
            this.dialogQueryFormVisible = true
        },

        getList() {
            console.log(111);
            this.listLoading = true
            queryPage(this.listQuery)
                .then(response => {
                    this.list = response.data.rows
                    this.total = response.data.total
                    this.listLoading = false
                    this.initData()
                })
                .catch(() => {
                    this.initData()
                })
        },
        initData() {
            this.submitIds = []
            this.submitList = []
        },
        handleFilter() {
            this.getList()
        },
        handleQuery() {
            this.listQuery.page = 1
            this.getList()
            this.dialogQueryFormVisible = false
        },
        // 是否显示树
        handleShowTree() {
            this.showTree = !this.showTree
        },
        // 树节点点击
        handleNodeClick(data) {
            if (!Object.prototype.hasOwnProperty.call(data, 'children')) {
                this.formData.toAgencyName = data.label
                // this.formData.agencyCode = data.code
                this.formData.outToAgency = data.id
            }
        },
        // 树过滤
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        handleAdd() {
            // this.$confirm('工资项名称只能填写汉字或英文小括号！', '提示', {
            //   closeOnClickModal: false,
            //   confirmButtonText: '确定',
            //   cancelButtonText: '取消',
            //   type: 'warning'
            // }).then(() => {
            const addItem = { ...this.addItem }
            addItem.isNewItem = Math.random()
                .toString(16)
                .substr(2, 8)
            this.list.unshift(addItem)
            this.submitList.push(addItem)
            // })
        },
        //修改
        handleEdit() {
            const selection = this.$refs.singalTable.selection
            // if (selection.length !== 1) {
            //     this.$message({
            //         message: '请选择一条数据',
            //         type: 'warning',
            //         showClose: true,
            //         duration: 4000
            //     })
            //     return
            // }

            if (!this.submitIds.includes(selection[0].id)) {
                for (let i = 0; i < selection.length; i++) {
                    this.$set(selection[i], 'isOperate', true)
                }
                this.submitIds.push(selection[0].id)
                this.submitList = selection
            }
        },

        handleRemove() {
            const selection = this.$refs.singalTable.selection
            if (selection.length === 0) {
                this.$message({
                    message: '请选择至少一条数据',
                    type: 'warning',
                    showClose: true,
                    duration: 4000
                })
                return
            }
            for (const select of selection) {
                if (
                    select.id === '46F1370C5F2A4D31AD196718A93DC470' ||
                    select.id === '3C4B5B347C9F420BB8D4B86572A5F178'
                ) {
                    this.$message({
                        message: '应发项和实发工资不可删除',
                        type: 'warning',
                        showClose: true,
                        duration: 4000
                    })
                    return
                }
            }
            this.removeBtnLoading = true
            this.$confirm('确定删除吗？', '提示', {
                closeOnClickModal: false,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    // 删除新增的数据
                    this.removeNewItem(selection)
                    // 删除数据库中的数据
                    if (this.ids) {
                        deleteBatchData(this.ids)
                            .then(() => {
                                this.$message({
                                    message: '删除成功',
                                    type: 'success',
                                    showClose: true,
                                    duration: 4000
                                })
                                this.handleFilter()
                                this.removeBtnLoading = false
                            })
                            .catch(() => {
                                this.removeBtnLoading = false
                            })
                    } else {
                        this.removeBtnLoading = false
                    }
                })
                .catch(() => {
                    this.removeBtnLoading = false
                })
        },

        removeNewItem(selection) {
            const newItemArr = []
            selection.forEach(item => {
                if (item.isNewItem) {
                    newItemArr.push(item.isNewItem)
                }
            })
            if (newItemArr.length > 0) {
                const list = this.list
                for (let i = 0; i < list.length; i++) {
                    if (newItemArr.indexOf(list[i].isNewItem) > -1) {
                        list.splice(i--, 1)
                    }
                }
                const submitList = this.submitList
                for (let i = 0; i < submitList.length; i++) {
                    if (newItemArr.indexOf(submitList[i].isNewItem) > -1) {
                        submitList.splice(i--, 1)
                    }
                }
            }
        },
        //保存
        handleSave() {
            const submitList = this.submitList
            if (submitList.length === 0) {
                this.$message({
                    message: '没有可保存的数据',
                    type: 'warning',
                    showClose: true,
                    duration: 2000
                })
                this.$emit("setSaveBtnLoading");

                return
            }
            console.log(submitList);
            for (const item of submitList) {
                if (!item.salaryName) {
                    this.$message({
                        message: '工资项名称为必填项',
                        type: 'warning',
                        showClose: true,
                        duration: 2000
                    })
                    this.$emit("setSaveBtnLoading");
                    return
                }
                if (item.computeFormula === "" || item.computeFormula === null || item.computeFormula === undefined) {
                    this.$message({
                        message: '工资项类型为必填项',
                        type: 'warning',
                        showClose: true,
                        duration: 2000
                    })
                    this.$emit("setSaveBtnLoading");
                    return
                }
                // else {
                //   const regex = /^[\u4e00-\u9fa5]*\(?[\u4e00-\u9fa5]*\)?[\u4e00-\u9fa5]*$/
                //   if (!regex.test(item.salaryName)) {
                //     this.$message({
                //       message: '工资项名称只能填写汉字或英文小括号！',
                //       type: 'warning',
                //       showClose: true,
                //       duration: 2000
                //     })
                //     return
                //   }
                // }
            }

            // this.$confirm('确定保存吗？', '提示', {
            //   closeOnClickModal: false,
            //   confirmButtonText: '确定',
            //   cancelButtonText: '取消',
            //   type: 'warning'
            // })
            //   .then(() => {
            if (submitList.salaryListOrder === '') {
                submitList.salaryListOrder = null
            }
            submitData(submitList)
                .then(response => {
                    this.$message({
                        message: '保存成功',
                        type: 'success',
                        showClose: true,
                        duration: 2000
                    })
                    this.handleFilter()
                    this.$emit("setSaveBtnLoading");
                })
                .catch(() => {
                    this.$emit("setSaveBtnLoading");
                })
            // })
            // .catch(() => {
            //   this.saveBtnLoading = false
            // })
        },
        selectable(row) {
            // 实发项和应发项复选框disable，不允许修改
            //   if (row.id == '0'|| row.code !=='0') { return false }{ return true}
            if (row.salaryCode === 's2') {
                return false;
            }
            if (row.salaryCode === 's1') {
                return false;
            } else {
                return true;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.app-title {
    margin-bottom: 15px;
    height: 20px;
    border-bottom: 1px solid #dcdfe6;
}

.button {
    float: right;
}

/** 文本框高度 **/
::v-deep .el-input {
    width: auto !important;
}
</style>
  